import React, {useEffect, useState, useRef} from 'react';
import {View, FlatList} from 'react-native';
import {Navigation, NavigationFunctionComponent} from 'react-native-navigation';
import {observer} from 'mobx-react';
import {Focusable, Text, Flex, Musicing} from '../components';
import {playlist_detail, song_detail} from '../apis';
import styled from 'styled-components/native';
import useWidth from '../hooks/useWidth';
import {usePlayer} from '../hooks/useStores';

const PAGESIZE = 50;

interface Props {
  detail: any;
}

const Container = styled.View`
  height: 100%;
  width: 100%;
`;

const SongBox = styled.View`
  height: 80px;
`;

const Song = styled(Flex)`
  width: 100%;
  height: 80px;
  background-color: rgba(0, 0, 0, 0.3);
  padding-right: 24px;
`;

const SongPic = styled.Image`
  height: 80px;
  width: 80px;
  margin-right: 12px;
`;

const Empty = styled(Flex)`
  height: 60px;
  width: 100%;
`;

interface ItemProps {
  item: any;
  onPress: any;
  playing: boolean;
  width: number;
}

class Item extends React.PureComponent<ItemProps> {
  render() {
    const {item, onPress, width, playing} = this.props;

    return (
      <SongBox style={{width}}>
        <Focusable onPress={onPress} ani>
          <Song align="center" justify="space-between">
            <SongPic
              source={{uri: `${item.al.picUrl}?param=80y80`}}
              resizeMode="cover"
            />
            <Flex
              direction="column"
              justify="space-evenly"
              style={{
                flex: 1,
              }}>
              <Text numberOfLines={1} ellipsizeMode="tail" size={24}>
                {item.name}
              </Text>
              <Text
                numberOfLines={1}
                ellipsizeMode="tail"
                color="rgba(255,255,255, 0.6)">
                {item.ar.map((ar: any) => ar.name).join('/')}
              </Text>
            </Flex>
            {playing ? (
              <View style={{marginLeft: 12}}>
                <Musicing width={18} height={18} />
              </View>
            ) : null}
          </Song>
        </Focusable>
      </SongBox>
    );
  }
}

const Playlist: NavigationFunctionComponent<Props> = observer(
  ({componentId, detail}) => {
    const page = useRef(1);
    const id = useRef(0);
    const ended = useRef(false);
    const loadlock = useRef(false);
    const [loading, setLoading] = useState<boolean>(false);
    const {w2} = useWidth();
    const [list, setList] = useState<any[]>([]);
    const [ids, setIds] = useState<number[]>([]);

    const {startPlayList, current} = usePlayer();

    useEffect(() => {
      if (detail) {
        id.current = Number(detail.id);
        setTitle();
        load();
      }
    }, [detail]);

    const setTitle = () => {
      Navigation.mergeOptions(componentId, {
        topBar: {
          title: {
            text: detail.name,
          },
        },
      });
    };

    const lock = () => {
      loadlock.current = true;
      setLoading(true);
    };

    const unlock = () => {
      loadlock.current = false;
      setLoading(false);
    };

    const load = async () => {
      try {
        lock();
        const {playlist, code, message}: any = await playlist_detail(detail.id);
        if (code !== 200) {
          unlock();
          await global.showToast({
            title: message,
          });
          Navigation.pop(componentId);
          return;
        }
        const {trackIds} = playlist;
        console.log('获取歌曲 id 首', trackIds.length);
        setIds(trackIds.map((i: any) => i.id));
      } catch (error) {
        console.log(error);
      }
      unlock();
    };

    useEffect(() => {
      ended.current = false;
      page.current = 1;
      setList([]);
      loadPage();
    }, [ids]);

    const loadPage = async () => {
      if (loadlock.current || ended.current) return;
      lock();
      try {
        const start = (page.current - 1) * PAGESIZE;
        const end = page.current * PAGESIZE;
        console.log('获取歌曲 页', page.current, start, end);
        const pids = ids.slice(start, end);
        if (pids.length === 0) {
          ended.current = true;
          unlock();
          return;
        }
        const {songs}: any = await song_detail(pids);
        setList([...list, ...songs]);
        console.log('获取歌曲 页...成功', songs.length);
        page.current++;
      } catch (error) {
        console.log(error);
      }
      unlock();
    };

    const renderItem = ({item}: any) => {
      return (
        <Item
          item={item}
          onPress={async () => {
            const ok: any = await startPlayList(id.current, item.id, ids);
            if (ok === false) {
              return;
            }
            showMusicPage();
          }}
          width={w2}
          playing={current?.id === item.id}
        />
      );
    };

    const showMusicPage = () => {
      Navigation.push(componentId, {
        component: {name: 'Music'},
      });
    };

    return (
      <Container>
        <FlatList
          horizontal={false}
          numColumns={2}
          style={{width: '100%', height: '100%'}}
          columnWrapperStyle={{
            justifyContent: 'space-between',
            paddingLeft: 30,
            paddingRight: 30,
            paddingTop: 10,
            paddingBottom: 10,
          }}
          data={list}
          renderItem={renderItem}
          keyExtractor={(item: any) => `${item.id}`}
          ListFooterComponent={
            <Empty align="center" justify="center">
              <Text color="rgba(255,255,255,0.6)">
                {loading ? '正在加载歌单...' : '没有更多歌曲了~'}
              </Text>
            </Empty>
          }
          onEndReachedThreshold={0.5}
          onEndReached={() => {
            loadPage();
          }}
        />
      </Container>
    );
  },
);

export default Playlist;
